package com.apes.scm.stock.profitAndLoss;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.DateUtil;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 功能：损益单
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ProfitAndLoss.CONST_TABLE_NAME)
public class ProfitAndLoss extends Model {
    public static final String CONST_TABLE_NAME = "stock_profit_loss";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "损溢单", prefix = "%(yy)%(month)", padding = 4, useDateRange=true)
    @Comment("损溢单号")
    private String id;

    @NotNull
   /* @States(name = "类型", values = {
            @State(id = "profit", name = "报溢"),
            @State(id = "loss", name = "报损")
    })*/
    @Column(name = "type",length = 8, nullable = false)
    @Comment("类型")
    private String type;

    @Column(name = "source", length = 30)
    @Comment("来源单据")
    private String source;

    @Column(name = "source_business_type", length = 32)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    @Comment("库存位置")
    private Location location;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "responsibility", referencedColumnName = "id", nullable = false)
    @Comment("责任方")
    private PartyRole responsibility;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "COMPANY_ID", referencedColumnName = "id", nullable = false)
    private PartyRole company;  //公司编码

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门编码")
    private Dept dept;

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "创建"),
            @State(id = "approve", name = "审核"),
            @State(id = "OA", name = "发起OA"),
            @State(id = "delete", name = "删除")
    })
    @Column(name = "state", length = 10, nullable = false)
    private String state;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审批人")
    private PartyRole approveUid;

    @Column(name = "date_approve")
    @Comment("审核日期")
    private Date dateApprove;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteId; //删除

    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate; //删除日期

    @Column (name ="note")
    @Comment("备注")
    private String note;

    @Column (name ="approve_note")
    @Comment("审核备注")
    private String approveNote;

    @Column (name ="OA_USER_ID")
    @Comment("OA发起人")
    private String OAUser;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("合同编码")
    private Contract contract;

    @OneToMany(mappedBy = "profitAndLoss", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ProfitAndLossItem> profitAndLossItems = new ArrayList<>();

    public List<ProfitAndLossItem> getProfitAndLossItems() {
        for(ProfitAndLossItem item : profitAndLossItems){
            if ("0.0".equals(item.getPriceUnit()+"") && "profit".equals(this.getType())) { // 单价不能为空，历史数据不判断
                long createDateTime = DateUtil.parseUTC(DateUtil.format(item.getCreateDate(), DateUtil.SHOW_DATETIME_UTC_FORMAT)).getTime();
                long appointDateTime = DateUtil.parseUTC(DateUtil.format(DateUtil.parse("2021-05-01 00:00:00"),  DateUtil.SHOW_DATETIME_UTC_FORMAT)).getTime();
                if (item.getCreateDate() != null && createDateTime > appointDateTime)
                    throw new RuntimeException("商品单价不能为0");
            }
            item.setProfitAndLoss(this);
        }
        return  profitAndLossItems;
    }

    @Transient
    private double amtTotal = 0;

    @Transient
    private String needSupperOA;

    public String getNeedSupperOA() {
        if (Objects.isNull(this.getCompany()))return null;
        return this.getCompany().getParty().getCorporate().getOperation().getDescription().equals("赋能店")?"0":"1";
    }

    public double getAmtTotal() {
        return getProfitAndLossItems().stream().mapToDouble(item->item.getPriceUnit()*item.getQty()).sum();
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }
}
